﻿var express = require('express');
var router = express.Router();
var connection = require('../backjs/node_mysql.js')


//分配各类派工单
router.post('/allot', function (req, res) {
    //检测主管
    if (req.body.requestType == 'manager') {
        //更新派工单小组编号等taskpaper
        var sql = 'update taskpaper,task set tp_team=?,tp_uid=?,tp_start=?,task_passTeam = task_passTeam+1  where tp_wcid = ? and task_id = tp_tid';
        var params = [req.body.tp_team, req.body.tp_uid, req.body.tp_start, req.body.tp_wcid];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
        });
        sql = 'select tech_id from tech where tech_wcid = ?';
        params = [req.body.tp_wcid];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            if (rs.length == 0) {
                sql = 'update task,taskpaper set task_tech=task_tech-1 where task_id = tp_tid and tp_wcid = ?';
                params = [req.body.tp_wcid];
                connection.query(sql, params, function (err, rs) {
                    if (err) {
                        throw err;
                    }
                    res.send(200);
                });
            }
            else {
                res.send(200);
            }
        });
    }
    //检测组长
    if (req.body.requestType == 'leader') {
        //新建dispatch记录
        var sql = 'insert into dispatch (d_tid,d_leader,d_tpid, d_uid, d_start,d_wcid) values ? ';
        var params = [[req.body.d_tid, req.body.d_leader, req.body.d_tpid, req.body.d_uid, req.body.d_start, req.body.d_wcid]];
        var disId;
        connection.query(sql, [params], function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                console.log(rs);
                disId = rs.insertId;
                //更新工件表中对应dispatch编号
                sql = 'update workpiece set w_did = ?,w_sid = ? where w_id in (?)';
                var values = [disId, req.body.d_uid, req.body.w_ids];
                connection.query(sql, values, function (err, rs) {
                    if (err) {
                        throw err;
                    }
                    else {
                        res.send(200);
                    }
                });
            }
        });
    }
});

//未分配工件数量查询并更新taskpaper状态
router.post('/wp_num', function (req, res) {
    var sql = 'update taskpaper set tp_state = 1 where tp_id = ? and not exists(select w_id from workpiece where w_wcid = tp_wcid and w_did is null)' 
    var params = [req.body.tp_id];
    connection.query(sql, params, function (err, rs) {
        if (err) {
            throw err;
        }
        else {
            res.send(200);
        }
    });
});



//taskpaper列表,派工单列表
router.post('/taskpaper_list', function (req, res) {
    //超级管理员
    if (req.body.requestType == 'superManager') {
        var sql = 'select tmp.*, task_pname, task_type, wc_num,tech_id from (select tp_id, tp_tid, tp_start,tp_wcid from taskpaper where ' +
            'tp_state = 0) tmp left join task on task_id = tp_tid left join workcount on wc_id = tp_wcid left join ' +
            'tech on tech_wcid = wc_id';//wc_num????
        connection.query(sql, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                console.log('超管拿到的未分配的数据：', rs)
                res.send(rs);
            }
        });
    }
    //检测主管
    if (req.body.requestType == 'manager') {
        var sql = 'select tp_id,task_pname,task_type,wc_num,tp_start,tp_state ' +
            'from taskpaper,task,workcount where task_department = ? and ' +
            'wc_tid = task_id and tp_wcid = wc_id and tp_state = 0';
        var params = [req.body.user_part];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                console.log(rs)
                res.send(rs);
            }
        });
    }
    //检测组长，未分配taskpaper
    if (req.body.requestType == 'leader') {
        var sql = 'select tmp.*, task_pname, task_type, wc_num,tech_id from (select tp_id, tp_tid, tp_start,tp_wcid from taskpaper where ' +
            'tp_uid = ? and tp_state = 0) tmp left join task on task_id = tp_tid left join workcount on wc_id = tp_wcid left join ' +
            'tech on tech_wcid = wc_id';//wc_num????
        var params = [req.body.user_id];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                res.send(rs);
            }
        });
    }
});

//dispatch列表
router.post('/dispatch_list', function (req, res, next) {
    if (req.body.requestType == 'superManager'){    //超管
        var sql = 'select tmp.* ,task_pname, task_type,tech_id from (select d_id,d_tid,d_tpid,d_start,d_fin,d_uid,d_wcid,user_name from dispatch, user ' +
            'where user_id = d_uid)tmp left join task on task_id = d_tid left join tech on tech_wcid = d_wcid order by d_id DESC ';
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                console.log('超管拿到的已分配的数据：', rs);
                res.send(rs);
            }
        });
    }
    if (req.body.requestType == 'manager'){ //检测主管
        var sql = 'select tmp.* ,task_pname, task_type,tech_id from (select d_id,d_tid,d_tpid,' +
            'd_start,d_fin,d_uid,d_wcid,user_name from dispatch, user where d_leader = ' +
            '(select team_uid from team where team_part = ?) and user_id = d_uid)tmp left ' +
            'join task on task_id = d_tid left join tech on tech_wcid = d_wcid order by d_id DESC';
        var params = [req.body.user_part];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                console.log(rs)
                res.send(rs);
            }
        });
    }
    //检测组长已分配列表
    if (req.body.requestType == 'leader') {
        var sql = 'select tmp.* ,task_pname, task_type,tech_id from (select d_id,d_tid,d_tpid,d_start,d_fin,d_uid,d_wcid,user_name from dispatch, user ' +
            'where d_leader = ? and user_id = d_uid)tmp left join task on task_id = d_tid left join tech on tech_wcid = d_wcid order by d_id DESC ';
        var params = [req.body.user_id];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                console.log(rs);
                throw err;
            }
            else {
                res.send(rs);
            }
        });

    }
    //检测人员
    if (req.body.requestType == 'worker') {
        var sql = 'select tmp.* ,task_pname, task_type,tech_id from (select d_id,d_tid,d_tpid,d_start,d_fin,d_uid,d_wcid from dispatch ' +
            'where d_uid = ? )tmp left join task on task_id = d_tid left join tech on tech_wcid = d_wcid order by d_id DESC';
        var params = [req.body.user_id];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            res.send(rs);
        });
    }
});

//未分配工件列表（检测组长）
router.post('/allotWorkpiece', function (req, res) {
    var sql = 'select w_id, w_pipeName,w_tid,w_pipeNum,w_weldNum,w_weldPer,w_re,w_photoNum,w_spec,w_texture, ' +
        'w_scale,w_type,w_weldM,w_weldTime,w_test,w_qua from workpiece  where w_wcid = ? and w_did is NULL';
    var params = [req.body.tp_wcid];
    connection.query(sql, params, function (err, rs) {
        if (err) {
            throw err;
        }
        else {
            res.send(rs);
        }
    });
});

//查看派工单详情
router.post('/checkTorDT', function (req, res) {
    //基本信息
    if (req.body.requestType == 'initBaseData') {
        var sql = 'select tmp.*,tech.* from (select task_product,task_opportunity, task_addr,task_level, task_time, task_pname, task_state, task_position, task_standard, wc_pipeName, wc_spec, ' +
            'wc_texture,wc_scale,wc_weldM,wc_test,wc_qua,wc_type,wc_num from workcount,task where wc_id = ? and task_id = wc_tid)tmp left join tech ' +
            'on tech_wcid = ?';
        var params = [req.body.wc_id, req.body.wc_id];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                res.send(rs);
            }
        });
    }
    else if (req.body.requestType == 'taskpaper') {
        //查看taskpaper详情
        var sql = 'select w_pipeName,w_pipeNum,w_weldNum,w_weldPer,w_re,w_photoNum,w_spec,w_texture,w_scale,w_type,w_weldM,w_weldTime,w_test,w_qua from ' +
            'workpiece where w_wcid = ?';
        var params = [req.body.wc_id];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                res.send(rs);
            }
        });

    }
    //查看dispatch详情
    else if (req.body.requestType == 'dispatch') {
        //接下来通过委托单id拿到：产品名称、委托单位、检测时机、检测标准
        var sql = 'select w_pipeName,w_pipeNum,w_weldNum,w_weldPer,w_re,w_photoNum,w_spec,w_texture,w_scale,w_type,w_weldM,w_weldTime,w_test,w_qua from ' +
            'workpiece where w_did = ?';
        var params = [req.body.d_id];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                res.send(rs);
            }
        });
    }
});

//操作记录页面
router.post('/operation', function (req, res) {

    //获取相关基本信息
    if (req.body.requestType == 'initBaseData') {
        var sql = 'select tmp.*,tech_id,tech_filmV,tech_filmBrand,tech_devTime,tech_devT,tech_focus,tech_liquor from(select task_product,task_company' +
            ',task_pname,task_id,task_opportunity,task_standard,task_level,task_check,wc_id,wc_scale,' +
            'wc_weldM,wc_pipeName,wc_texture,task_heat,task_position from task,workcount where task_id = ? and wc_id = ?) tmp left join tech on tech_wcid = wc_id ';
        var params = [req.body.d_tid, req.body.d_wcid];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                res.send(rs);
            }
        });
    }
    //获取操作记录改写后的基本信息
    if (req.body.requestType == 'initOpData') {
        var sql = 'select operation.*,task_product,task_company,wc_pipeName,task_heat,task_position' +
            ',task_pname,task_id,task_opportunity,task_standard,task_level,task_check from operation,' +
            'dispatch,workcount,task where d_id = ? and d_opid = op_id and task_id = ? and wc_id =?';
        var params = [req.body.w_did, req.body.task_id, req.body.wc_id];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                var sql = 'select * from workpiece where w_did = ? and w_state > 0';
                var params = [req.body.w_did];
                connection.query(sql, params, function (err_, rs_) {
                    if (err_) {
                        throw err_;
                    }
                    else {
                        res.send({
                            "base": rs,
                            "workpiece": rs_
                        });
                    }
                });
            }
        });
    }
    //获取派工单下的工件列表
    if (req.body.requestType == 'initWorkpieceData') {
        var sql = 'select w_id,w_weldNum,w_pipeNum from workpiece where w_did = ? and w_state = 0';
        var params = [req.body.w_did];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                res.send(rs);
            }
        });
    }
    //新建操作记录（基本信息插入）
    if (req.body.requestType == 'updateBaseData') {
        var sql = 'insert into operation(op_tid,op_techid,op_weldM,op_texture,op_focus,op_equ,op_equid,op_sensitizer,' +
            'op_filmV, op_filmBrand,op_devTime,op_devT,op_scale,op_liquor,op_remark,op_photo,op_pdate,op_wash,op_wdate,op_front,op_rear) values ?';
        var params = [[req.body.op_tid, (req.body.op_techid == "" ? null : req.body.op_techid), req.body.op_weldM, req.body.op_texture,
        req.body.op_focus, req.body.op_equ, req.body.op_equid, req.body.op_sensitizer, req.body.op_filmV, req.body.op_filmBrand,
        req.body.op_devTime, req.body.op_devT, req.body.op_scale, req.body.op_liquor, req.body.op_remark,
        req.body.op_photo, req.body.op_pdate, req.body.op_wash, req.body.op_wdate, req.body.op_front, req.body.op_rear]];//tech_id为空则输入0
        var opId;
        connection.query(sql, [params], function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                opId = rs.insertId;//移到里面！！！
                sql = 'update dispatch set d_opid = ? where d_id = ?';
                var values = [opId, req.body.d_id];
                connection.query(sql, values, function (err, rs) {
                    if (err) {
                        throw err;
                    }
                    else {
                        res.send(200);
                    }
                });
            }
        });
        //更新diapatch中的操作记录id

    }
    //更新工件信息
    if (req.body.requestType == 'updateWorkpieceData') {
        var sql = 'insert into workpiece (w_id, w_rspec ,w_V ,w_A  ,w_time ,w_phoNum  ,w_tranType ,w_IQIV ,w_pos, w_state) values ? on duplicate key update ' +
            'w_rspec=values(w_rspec) ,w_V=values(w_V) ,w_A=values(w_A)  ,w_time=values(w_time) ,w_phoNum=values(w_phoNum)  ,w_tranType=values(w_tranType) ,w_IQIV=values(w_IQIV) ,w_pos=values(w_pos), w_state=values(w_state)';
        var params = [];
        var num = req.body.num;
        if (num == 1) {
            params = [[req.body.w_id, req.body.w_rspec, req.body.w_V, req.body.w_A, req.body.w_time,
                req.body.w_phoNum, req.body.w_tranType, req.body.w_IQIV, req.body.w_pos, 1]];
        } else {
            for (var i = 0; i < num; i++) {
                var vec = [req.body.w_id[i], req.body.w_rspec[i], req.body.w_V[i], req.body.w_A[i],
                    req.body.w_time[i], req.body.w_phoNum[i], req.body.w_tranType[i], req.body.w_IQIV[i], req.body.w_pos[i], 1];
                params.push(vec);
            }
        }
        connection.query(sql, [params], function (err, rs) {
            if (err) {
                throw err;
            } else {
                sql = 'insert into photo (ph_wid,ph_client,ph_part,ph_spec,ph_phNum) values ?';
                params = [];
                var num = req.body.num;
                for (var i = 0; i < num; i++) {
                    if (num == 1) {
                        //var temp = req.body.ph_phNum;
                        for (var j = 1; j <= req.body.w_phoNum; j++) {
                            var vec = [req.body.w_id, req.body.ph_client, req.body.user_part, req.body.w_rspec, j];
                            params.push(vec);
                        }
                    } else {
                        for (var j = 1; j < req.body.w_phoNum[i]; j++) {
                            var vec = [req.body.w_id[i], req.body.ph_client, req.body.user_part, req.body.w_rspec[i], j];
                            params.push(vec);
                            }
                        }
                    }
                }
                console.log(params);
                connection.query(sql, [params], function (err, rs) {
                    if (err) {
                        throw err;
                    }
                    else {
                        res.send(200);
                    }
                });

        });
    }

    //检查并更新各种状态和结束时间
    if (req.body.requestType == 'updateState') {
        //如果派工单（dispatch）下不存在没操作过的工件，就更改状态为1
        var sql = 'update dispatch set d_state = 1, d_fin =? where d_id = ? and not exists(select w_state from workpiece where w_did =d_id and w_state = 0)'
        var params = [req.body.d_fin, req.body.d_id];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                //如果派工单（taskpaper)下所有的dispatch都已完成，则更改状态为2
                sql ='update taskpaper set tp_state = 2,tp_fin = ? where tp_id =? and not exists(select d_state from dispatch where d_state = 0 and d_tpid = tp_id)'
                params = [req.body.d_fin, req.body.d_tpid];
                connection.query(sql, params, function (err, rs) {
                    if (err) {
                        throw err;
                    }
                    else {
                        res.send(200);
                    }
                });
            }
        });
    }
    //获取当前客户id和部门编号
    if (req.body.requestType == 'selectClient') {
        var sql = 'select task_uid, task_department from task where task_id = ?';
        var params = [req.body.d_tid];
        connection.query(sql, params, function (err, rs) {
            if (err) {
                throw err;
            }
            else {
                res.send(rs);
            }
        });
    }
});

//检测主管获取未填写评片记录
router.post('/photo_list', function (req, res, next) {
    if(req.body.role == 'superManager'){
        if (req.body.requestType == "history") {
            var sql = 'select photo.*,w_pipeNum,w_weldNum,w_weldPer,w_spec from photo,workpiece where ' +
                'w_id = ph_wid and ph_state = 1';
            connection.query(sql, function (err, rs) {
                if (err) {
                    throw err;
                }
                else {
                    //console.log(rs);
                    res.send(rs);
                }
            });
        }
        else if (req.body.requestType == "now") {
            var sql = 'select ph_id,w_pipeNum,w_weldNum,w_weldPer,w_spec,ph_phNum from photo,workpiece where ' +
                'w_id = ph_wid and ph_state = 0';
            connection.query(sql, function (err, rs) {
                if (err) {
                    throw err;
                }
                else {
                    res.send(rs);
                }
            });
        }
    }else if(req.body.role == 'Manager'){
        if (req.body.requestType == "history") {
            var sql = 'select photo.*,w_pipeNum,w_weldNum,w_weldPer,w_spec from photo,workpiece where ' +
                'w_id = ph_wid and ph_part = ? and ph_state = 1';
            var params = [req.body.user_part];
            connection.query(sql, params, function (err, rs) {
                if (err) {
                    throw err;
                }
                else {
                    //console.log(rs);
                    res.send(rs);
                }
            });
        }
        else if (req.body.requestType == "now") {
            var sql = 'select ph_id,w_pipeNum,w_weldNum,w_weldPer,w_spec,ph_phNum from photo,workpiece where ' +
                'w_id = ph_wid and ph_part = ? and ph_state = 0';
            var params = [req.body.user_part];
            connection.query(sql, params, function (err, rs) {
                if (err) {
                    throw err;
                }
                else {
                    res.send(rs);
                }
            });
        }
    }
});

//提交评片记录
router.post('/photo_update', function (req, res, next) {
    var sql = 'insert into photo (ph_id,ph_IQISen,ph_bmin,ph_bmax,ph_quality,ph_situation,ph_flaw,ph_pos,ph_size, ph_evalevel, ph_conclusion, ph_state,ph_time) values ? ON DUPLICATE KEY UPDATE ' +
        'ph_IQISen=values(ph_IQISen),ph_bmin=values(ph_bmin),ph_bmax=values(ph_bmax),ph_quality=values(ph_quality),ph_situation=values(ph_quality),ph_flaw=values(ph_flaw),ph_pos=values(ph_pos),' +
        'ph_size=values(ph_size), ph_evalevel=values(ph_evalevel), ph_conclusion=values(ph_conclusion), ph_state=values(ph_state),ph_time=values(ph_time)';
    var num = req.body.num;
    var params = [];
    for (var i = 0; i < num; i++) {
        var vec = [req.body.ph_id[i], req.body.ph_IQISen[i], req.body.ph_bmin[i], req.body.ph_bmax[i],
            req.body.ph_quality[i],req.body.ph_situation[i],
        req.body.ph_flaw[i], req.body.ph_pos[i], req.body.ph_size[i], req.body.ph_evalevel[i], req.body.ph_conclusion[i], 1, req.body.ph_time];
        if (num == 1) {
            vec = [req.body.ph_id, req.body.ph_IQISen, req.body.ph_bmin, req.body.ph_bmax,
                req.body.ph_quality[i],req.body.ph_situation[i],
            req.body.ph_flaw, req.body.ph_pos, req.body.ph_size, req.body.ph_evalevel, req.body.ph_conclusion, 1, req.body.ph_time];
        }
        params.push(vec);
    }
    connection.query(sql, [params], function (err, rs) {
        if (err) {
            throw err;
        }
        else {
            //如果这个工件下拥有评片记录而且全部被评完了，则更改状态为2
            sql = 'update workpiece set w_state = 2 where exists(select ph_id from photo where ph_wid = w_id) and not exists (select ph_id from photo where ph_state = 0 and ph_wid = w_id)'
            connection.query(sql, function (err, rs) {
                if (err) {
                    throw err;
                }
                else {
                    sql = 'update task set task_state = 1,task_fin = ? where not exists(select w_id from workpiece where w_tid = task_id and w_state<>2)'
                    params = [req.body.task_fin]
                    connection.query(sql, params,function (err, rs) {
                        if (err) {
                            throw err;
                        }
                        else {
                            
                            res.send(200);
                        }
                    });
                }
            });
        }
    });
});

module.exports = router;
